package org.jeecg.modules.demo.ddyht.controller;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.ddyht.entity.DdygPici;
import org.jeecg.modules.demo.ddyht.entity.DdygSale;
import org.jeecg.modules.demo.ddyht.entity.JxcCosting;
import org.jeecg.modules.demo.ddyht.entity.JxcCostingpici;
import org.jeecg.modules.demo.ddyht.service.IJxcCostingService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 成本核算
 * @Author: jeecg-boot
 * @Date: 2025-05-23
 * @Version: V1.0
 */
@Api(tags = "成本核算")
@RestController
@RequestMapping("/ddyht/jxcCosting")
@Slf4j
public class JxcCostingController extends JeecgController<JxcCosting, IJxcCostingService> {
    @Autowired
    private IJxcCostingService jxcCostingService;

    /**
     * 分页列表查询
     *
     * @param jxcCosting
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "成本核算-分页列表查询")
    @ApiOperation(value = "成本核算-分页列表查询", notes = "成本核算-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<JxcCosting>> queryPageList(JxcCosting jxcCosting,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        QueryWrapper<JxcCosting> queryWrapper = QueryGenerator.initQueryWrapper(jxcCosting, req.getParameterMap());
        Page<JxcCosting> page = new Page<JxcCosting>(pageNo, pageSize);
        IPage<JxcCosting> pageList = jxcCostingService.page(page, queryWrapper);

        List<JxcCosting> company = jxcCostingService.getBycompany(jxcCosting.getUsername());
        if (StringUtils.isNotBlank(jxcCosting.getType1())) {
            List<JxcCosting> list = new ArrayList<>();
            String type1 = jxcCosting.getType1();
            if (type1.equals("only")) {
                if (jxcCosting.getType2().equals("time")) {
                    if (StringUtils.isBlank(jxcCosting.getBeginTime()) || jxcCosting.getBeginTime() == null || jxcCosting.getBeginTime() == "") {
                        int size = company.size();
                        int page2 = (size + 9) / 10;
                        pageList.setTotal(size);
                        pageList.setPages(page2);
                        pageList.setRecords(company);
                        return Result.OK(pageList);
                    }
                    for (int i = 0; i < company.size(); i++) {
                        // company.get(i).getCreateTime()日期格式2025/04/27
                        String beginTime = jxcCosting.getBeginTime();
                        String endTime = jxcCosting.getEndTime();
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                        LocalDate startDate = LocalDate.parse(beginTime, formatter);
                        LocalDate endDate = LocalDate.parse(endTime, formatter);
                        log.info("company.get(i).getCreateTime().substring(0,10)：" + company.get(i).getCreateTime().substring(0, 10));
                        LocalDate createDate = LocalDate.parse(company.get(i).getCreateTime().substring(0, 10), formatter);
                        if (!createDate.isBefore(startDate) && !createDate.isAfter(endDate)) {
                            list.add(company.get(i));
                        }
                    }
                }
                if (jxcCosting.getType2().equals("model")) {
                    if (StringUtils.isBlank(jxcCosting.getType3())) {
                        int size = company.size();
                        int page2 = (size + 9) / 10;
                        pageList.setTotal(size);
                        pageList.setPages(page2);
                        pageList.setRecords(company);
                        return Result.OK(pageList);
                    }
                    String type3 = jxcCosting.getType3();
                    for (int i = 0; i < company.size(); i++) {
                        if (StringUtils.containsIgnoreCase(company.get(i).getModel(), type3)) {
                            list.add(company.get(i));
                        }
                    }
                }
                if (jxcCosting.getType2().equals("traner")) {
                    if (StringUtils.isBlank(jxcCosting.getType3())) {
                        int size = company.size();
                        int page2 = (size + 9) / 10;
                        pageList.setTotal(size);
                        pageList.setPages(page2);
                        pageList.setRecords(company);
                        return Result.OK(pageList);
                    }
                    String type3 = jxcCosting.getType3();
                    for (int i = 0; i < company.size(); i++) {
                        if (StringUtils.containsIgnoreCase(company.get(i).getBuyer(), type3)) {
                            list.add(company.get(i));
                        }
                    }
                }
            } else if (type1.equals("all")) {
                if (StringUtils.isNotBlank(jxcCosting.getBeginTime()) && jxcCosting.getBeginTime() != null && jxcCosting.getBeginTime() != "") {
                    for (int i = 0; i < company.size(); i++) {
                        // company.get(i).getCreateTime()日期格式2025/04/27
                        String beginTime = jxcCosting.getBeginTime();
                        String endTime = jxcCosting.getEndTime();
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                        LocalDate startDate = LocalDate.parse(beginTime, formatter);
                        LocalDate endDate = LocalDate.parse(endTime, formatter);
                        LocalDate createDate = LocalDate.parse(company.get(i).getCreateTime().substring(0, 10), formatter);
                        if (!createDate.isBefore(startDate) && !createDate.isAfter(endDate)) {
//						if (StringUtils.containsIgnoreCase(company.get(i).getModel(),type2)&& StringUtils.containsIgnoreCase(company.get(i).getBuyer(),type3)){
                            if (StringUtils.isNotBlank(jxcCosting.getType2()) && StringUtils.isNotBlank(jxcCosting.getType3())) {
                                String type2 = jxcCosting.getType2();
                                String type3 = jxcCosting.getType3();
                                if (type3.equals(company.get(i).getBuyer())) {
                                    if (StringUtils.containsIgnoreCase(company.get(i).getModel(), type2)) {
                                        list.add(company.get(i));
                                    }
                                }
                            } else if (StringUtils.isNotBlank(jxcCosting.getType2()) && StringUtils.isBlank(jxcCosting.getType3())) {
                                String type2 = jxcCosting.getType2();
                                if (StringUtils.containsIgnoreCase(company.get(i).getModel(), type2)) {
                                    list.add(company.get(i));
                                }
                            } else if (StringUtils.isBlank(jxcCosting.getType2()) && StringUtils.isNotBlank(jxcCosting.getType3())) {
                                String type3 = jxcCosting.getType3();
                                if (type3.equals(company.get(i).getBuyer())) {
                                    list.add(company.get(i));
                                }
                            } else if (StringUtils.isBlank(jxcCosting.getType2()) && StringUtils.isBlank(jxcCosting.getType3())) {
                                return Result.error("参数为空");
                            }
                        }
                    }
                } else if (StringUtils.isNotBlank(jxcCosting.getType2()) && StringUtils.isNotBlank(jxcCosting.getType3())) {
                    for (int i = 0; i < company.size(); i++) {
                        String type2 = jxcCosting.getType2();
                        String type3 = jxcCosting.getType3();
                        if (type3.equals(company.get(i).getBuyer())) {
                            if (StringUtils.containsIgnoreCase(company.get(i).getModel(), type2)) {
                                list.add(company.get(i));
                            }
                        }
                    }
                } else {
                    return Result.error("参数不足");
                }
            }
            int size = list.size();
            int page2 = (size + 9) / 10;
            pageList.setTotal(size);
            pageList.setPages(page2);
            pageList.setRecords(list);
            return Result.OK(pageList);
        }
		int size = company.size();
		int page2 = (size + 9) / 10;
		pageList.setTotal(size);
		pageList.setPages(page2);
		pageList.setRecords(company);
		return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param jxcCosting
     * @return
     */
    @AutoLog(value = "成本核算-添加")
    @ApiOperation(value = "成本核算-添加", notes = "成本核算-添加")
    @RequiresPermissions("ddyht:jxc_costing:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody JxcCosting jxcCosting) {
        jxcCostingService.save(jxcCosting);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param jxcCosting
     * @return
     */
    @AutoLog(value = "成本核算-编辑")
    @ApiOperation(value = "成本核算-编辑", notes = "成本核算-编辑")
    @RequiresPermissions("ddyht:jxc_costing:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody JxcCosting jxcCosting) {
        jxcCostingService.updateById(jxcCosting);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "成本核算-通过id删除")
    @ApiOperation(value = "成本核算-通过id删除", notes = "成本核算-通过id删除")
    @RequiresPermissions("ddyht:jxc_costing:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        jxcCostingService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "成本核算-批量删除")
    @ApiOperation(value = "成本核算-批量删除", notes = "成本核算-批量删除")
    @RequiresPermissions("ddyht:jxc_costing:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.jxcCostingService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "成本核算-通过id查询")
    @ApiOperation(value = "成本核算-通过id查询", notes = "成本核算-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<JxcCosting> queryById(@RequestParam(name = "id", required = true) String id) {
        JxcCosting jxcCosting = jxcCostingService.getById(id);
        if (jxcCosting == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(jxcCosting);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param jxcCostingpici
     */
    @RequiresPermissions("ddyht:jxc_costing:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, JxcCostingpici jxcCostingpici) {
        return exportXls2(request, jxcCostingpici, JxcCostingpici.class, "成本核算");
    }

//    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls2(HttpServletRequest request, JxcCostingpici object, Class<JxcCostingpici> clazz, String title) {
        // Step.1 组装查询条件
        QueryWrapper<JxcCostingpici> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 过滤选中数据
        String selections = request.getParameter("selections");
        log.info("selections {}", selections);
        if (oConvertUtils.isNotEmpty(selections)) {
            log.info("selections {}", selections);
            List<String> selectionList = Arrays.asList(selections.split(","));
            log.info("selectionList {}", selectionList);
            queryWrapper.in("id",selectionList);
        }
        List<JxcCostingpici> exportList = new ArrayList<JxcCostingpici>();
        // Step.2 获取导出数据
        if (oConvertUtils.isNotEmpty(selections)){
            List<String> selectionList = Arrays.asList(selections.split(","));
            List<JxcCostingpici> jxcCostingpicis = new ArrayList<JxcCostingpici>();
            for (int i = 0; i < selectionList.size(); i++) {
                String id = selectionList.get(i);
                jxcCostingpicis = jxcCostingService.getByallId(object.getUsername(), id);
                for (int i1 = 0; i1 < jxcCostingpicis.size(); i1++) {
                    jxcCostingpicis.get(i1).setTime(id.substring(0, 8));
                    exportList.add(jxcCostingpicis.get(i1));
                }
            }
        }else {
            List<JxcCostingpici> bycompanySale = jxcCostingService.getBycompanyOr(object.getUsername(), "成本核算");
            for (int i = 0; i < bycompanySale.size(); i++) {
                bycompanySale.get(i).setTime(bycompanySale.get(i).getId().substring(0, 8));
            }
            exportList = bycompanySale;
        }
        log.info("exportList {}", exportList);
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
//        exportList.sort((o1, o2) -> {
//            LocalDate date1 = LocalDate.parse(o1.getTime(), formatter);
//            LocalDate date2 = LocalDate.parse(o2.getTime(), formatter);
//            return date2.compareTo(date1); // 最新在前
//        });
//		 List<DdygSale> exportList = service.list(queryWrapper);

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, clazz);
        ExportParams exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
        exportParams.setImageBasePath("C:/upload/sc");
        mv.addObject(NormalExcelConstants.PARAMS,exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("ddyht:jxc_costing:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, JxcCosting.class);
    }

}
